<?php
declare(strict_types=1);

namespace app\controller\merchant;

use app\BaseController;
use app\model\{User, Order, UserBalanceFlow, UserPackage, PlatformOperationLog, UserRefundRecord};
use think\facade\{Db, Log, Cache};
use think\Request;

class UserController extends BaseController
{
    /**
     * 获取用户列表
     */
    public function list(Request $request)
    {
        try {
            $params = $request->get();
            $merchant_id = $request->merchant_id;
            $page = $params['page'] ?? 1;
            $limit = $params['limit'] ?? 15;
            
            $where = [['merchant_id', '=', $merchant_id]];
            
            // 搜索条件
            if (!empty($params['keyword'])) {
                $keyword = $params['keyword'];
                $where[] = ['mobile|real_name', 'like', "%{$keyword}%"];
            }
            
            // 注册时间筛选
            if (!empty($params['start_time'])) {
                $where[] = ['create_time', '>=', $params['start_time']];
            }
            if (!empty($params['end_time'])) {
                $where[] = ['create_time', '<=', $params['end_time']];
            }
            
            $list = User::where($where)
                ->withCount(['orders', 'packages'])
                ->order('id', 'desc')
                ->paginate([
                    'list_rows' => $limit,
                    'page' => $page
                ]);
            
            return json(['code' => 0, 'msg' => '获取成功', 'data' => $list]);
        } catch (\Exception $e) {
            Log::error('获取用户列表失败: ' . $e->getMessage());
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 获取用户详情
     */
    public function detail(Request $request, $id)
    {
        try {
            $merchant_id = $request->merchant_id;
            
            $user = User::where([
                'id' => $id,
                'merchant_id' => $merchant_id
            ])->find();
            
            if (!$user) {
                return json(['code' => 1, 'msg' => '用户不存在']);
            }
            
            // 获取用户统计数据
            $stats = [
                // 订单统计
                'order_stats' => [
                    'total_count' => Order::where(['user_id' => $id])->count(),
                    'total_amount' => Order::where(['user_id' => $id])->sum('fee_actual'),
                    'month_count' => Order::where(['user_id' => $id])
                        ->whereTime('create_time', 'month')
                        ->count(),
                    'month_amount' => Order::where(['user_id' => $id])
                        ->whereTime('create_time', 'month')
                        ->sum('fee_actual')
                ],
                // 余额变动统计
                'balance_stats' => [
                    'total_recharge' => UserBalanceFlow::where([
                        'user_id' => $id,
                        'type' => 1 // 充值
                    ])->sum('balance_change'),
                    'total_consume' => UserBalanceFlow::where([
                        'user_id' => $id,
                        'type' => 3 // 消费
                    ])->sum('balance_change')
                ],
                // 会员套餐统计
                'package_stats' => [
                    'total_buy' => UserPackage::where(['user_id' => $id])->count(),
                    'current_package' => UserPackage::where([
                        'user_id' => $id,
                        'status' => 1 // 生效中
                    ])->find()
                ]
            ];
            
            $data = [
                'user_info' => $user,
                'stats' => $stats
            ];
            
            return json(['code' => 0, 'msg' => '获取成功', 'data' => $data]);
        } catch (\Exception $e) {
            Log::error('获取用户详情失败: ' . $e->getMessage());
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 获取用户订单列表
     */
    public function orderList(Request $request)
    {
        try {
            $params = $request->get();
            $merchant_id = $request->merchant_id;
            $user_id = $params['user_id'] ?? 0;
            $page = $params['page'] ?? 1;
            $limit = $params['limit'] ?? 15;
            
            if (!$user_id) {
                return json(['code' => 1, 'msg' => '参数错误']);
            }
            
            $where = [
                ['merchant_id', '=', $merchant_id],
                ['user_id', '=', $user_id]
            ];
            
            // 订单状态筛选
            if (isset($params['status'])) {
                $where[] = ['status', '=', $params['status']];
            }
            
            $list = Order::where($where)
                ->with(['coupon'])
                ->order('id', 'desc')
                ->paginate([
                    'list_rows' => $limit,
                    'page' => $page
                ]);
            
            return json(['code' => 0, 'msg' => '获取成功', 'data' => $list]);
        } catch (\Exception $e) {
            Log::error('获取用户订单列表失败: ' . $e->getMessage());
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 获取用户余额流水
     */
    public function balanceFlow(Request $request)
    {
        try {
            $params = $request->get();
            $merchant_id = $request->merchant_id;
            $user_id = $params['user_id'] ?? 0;
            $page = $params['page'] ?? 1;
            $limit = $params['limit'] ?? 15;
            
            if (!$user_id) {
                return json(['code' => 1, 'msg' => '参数错误']);
            }
            
            $where = [
                ['merchant_id', '=', $merchant_id],
                ['user_id', '=', $user_id]
            ];
            
            // 流水类型筛选
            if (isset($params['type'])) {
                $where[] = ['type', '=', $params['type']];
            }
            
            $list = UserBalanceFlow::where($where)
                ->order('id', 'desc')
                ->paginate([
                    'list_rows' => $limit,
                    'page' => $page
                ]);
            
            return json(['code' => 0, 'msg' => '获取成功', 'data' => $list]);
        } catch (\Exception $e) {
            Log::error('获取用户余额流水失败: ' . $e->getMessage());
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 拉黑/取消拉黑用户
     */
    public function setStatus(Request $request)
    {
        Db::startTrans();
        try {
            $params = $request->post();
            $merchant_id = $request->merchant_id;
            
            if (!isset($params['user_id']) || !isset($params['status'])) {
                return json(['code' => 1, 'msg' => '参数错误']);
            }
            
            $user = User::where([
                'id' => $params['user_id'],
                'merchant_id' => $merchant_id
            ])->find();
            
            if (!$user) {
                return json(['code' => 1, 'msg' => '用户不存在']);
            }
            
            // 更新用户状态
            $updateData = [
                'status' => $params['status'],
                'update_time' => date('Y-m-d H:i:s')
            ];
            
            // 如果是拉黑操作，记录原因和时间
            if ($params['status'] == 1) {
                if (empty($params['reason'])) {
                    return json(['code' => 1, 'msg' => '请填写拉黑原因']);
                }
                $updateData['blacklist_reason'] = $params['reason'];
                $updateData['blacklist_time'] = date('Y-m-d H:i:s');
            } else {
                // 取消拉黑时清空相关信息
                $updateData['blacklist_reason'] = '';
                $updateData['blacklist_time'] = null;
            }
            
            $user->save($updateData);
            
            // 记录操作日志
            PlatformOperationLog::create([
                'merchant_id' => $merchant_id,
                'operation_type' => $params['status'] == 0 ? '取消拉黑用户' : '拉黑用户',
                'operation_content' => "用户ID:{$params['user_id']}, 手机号:{$user->mobile}" . 
                    ($params['status'] == 1 ? ", 原因:{$params['reason']}" : ''),
                'create_time' => date('Y-m-d H:i:s')
            ]);
            
            Db::commit();
            return json(['code' => 0, 'msg' => '操作成功']);
        } catch (\Exception $e) {
            Db::rollback();
            Log::error('设置用户状态失败: ' . $e->getMessage());
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 获取黑名单列表
     */
    public function blacklist(Request $request)
    {
        try {
            $params = $request->get();
            $merchant_id = $request->merchant_id;
            $page = $params['page'] ?? 1;
            $limit = $params['limit'] ?? 15;
            
            $where = [
                ['merchant_id', '=', $merchant_id],
                ['status', '=', 1] // 已拉黑
            ];
            
            // 搜索条件
            if (!empty($params['keyword'])) {
                $keyword = $params['keyword'];
                $where[] = ['mobile|real_name', 'like', "%{$keyword}%"];
            }
            
            $list = User::where($where)
                ->withCount(['orders'])
                ->order('id', 'desc')
                ->paginate([
                    'list_rows' => $limit,
                    'page' => $page
                ]);
            
            return json(['code' => 0, 'msg' => '获取成功', 'data' => $list]);
        } catch (\Exception $e) {
            Log::error('获取黑名单列表失败: ' . $e->getMessage());
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 检查自动拉黑规则
     */
    protected function checkAutoBlacklist($user_id)
    {
        try {
            $user = User::find($user_id);
            if (!$user || $user->status == 1) {
                return;
            }
            
            // 规则1: 连续3次订单取消
            $cancelCount = Order::where([
                'user_id' => $user_id,
                'status' => 99 // 已取消
            ])->whereTime('create_time', '-7 days')
            ->count();
            
            if ($cancelCount >= 3) {
                $this->blacklistUser($user, '系统自动拉黑:7天内连续取消3次订单');
                return;
            }
            
            // 规则2: 恶意退款
            $refundCount = UserRefundRecord::where([
                'user_id' => $user_id,
                'status' => 1 // 已退款
            ])->whereTime('create_time', '-30 days')
            ->count();
            
            if ($refundCount >= 5) {
                $this->blacklistUser($user, '系统自动拉黑:30天内退款次数过多');
                return;
            }
            
            // 规则3: 余额异常
            $abnormalCount = UserBalanceFlow::where([
                'user_id' => $user_id,
                'type' => ['in', [1, 2]], // 充值和提现
                'status' => 2 // 异常
            ])->whereTime('create_time', '-90 days')
            ->count();
            
            if ($abnormalCount >= 2) {
                $this->blacklistUser($user, '系统自动拉黑:资金操作异常');
                return;
            }
            
        } catch (\Exception $e) {
            Log::error('检查自动拉黑规则失败: ' . $e->getMessage());
        }
    }

    /**
     * 执行拉黑操作
     */
    protected function blacklistUser($user, $reason)
    {
        Db::startTrans();
        try {
            // 更新用户状态
            $user->save([
                'status' => 1,
                'blacklist_reason' => $reason,
                'blacklist_time' => date('Y-m-d H:i:s'),
                'update_time' => date('Y-m-d H:i:s')
            ]);
            
            // 记录操作日志
            PlatformOperationLog::create([
                'merchant_id' => $user->merchant_id,
                'operation_type' => '系统自动拉黑用户',
                'operation_content' => "用户ID:{$user->id}, 手机号:{$user->mobile}, 原因:{$reason}",
                'create_time' => date('Y-m-d H:i:s')
            ]);
            
            Db::commit();
            
            // 发送通知
            event('user_blacklisted', $user);
            
        } catch (\Exception $e) {
            Db::rollback();
            Log::error('自动拉黑用户失败: ' . $e->getMessage());
        }
    }

    /**
     * 用户列表
     */
    public function index(Request $request)
    {
        $where = [
            ['merchant_id', '=', $request->merchantId]
        ];
        
        // 关键词搜索
        if ($keyword = $request->param('keyword')) {
            $where[] = ['mobile|real_name', 'like', "%{$keyword}%"];
        }
        
        $list = User::where($where)
            ->field('id, real_name, mobile, balance, create_time')
            ->order('id', 'desc')
            ->paginate([
                'list_rows' => $request->param('limit', 15),
                'page' => $request->param('page', 1)
            ]);
            
        return $this->success('获取成功', $list);
    }
    
    /**
     * 用户登录记录
     */
    public function loginLogs(Request $request)
    {
        $userId = $request->param('user_id');
        if (!$userId) {
            return $this->error('参数错误');
        }
        
        $list = Db::name('user_login_log')
            ->where('user_id', $userId)
            ->field('id, ip, country, province, city, district, isp, create_time')
            ->order('id', 'desc')
            ->paginate([
                'list_rows' => $request->param('limit', 15),
                'page' => $request->param('page', 1)
            ]);
            
        return $this->success('获取成功', $list);
    }
    
    /**
     * 用户地区分布统计
     */
    public function areaStats(Request $request)
    {
        // 先查询缓存
        $cacheKey = 'user_area_stats:' . $request->merchantId;
        if ($stats = Cache::get($cacheKey)) {
            return $this->success('获取成功', $stats);
        }
        
        // 统计省份分布
        $provinceStats = Db::name('user_login_log')
            ->alias('l')
            ->join('user u', 'l.user_id = u.id')
            ->where('u.merchant_id', $request->merchantId)
            ->where('l.province', '<>', '')
            ->field('l.province, COUNT(DISTINCT l.user_id) as user_count')
            ->group('l.province')
            ->select()
            ->toArray();
            
        // 统计城市分布(TOP 10)
        $cityStats = Db::name('user_login_log')
            ->alias('l')
            ->join('user u', 'l.user_id = u.id')
            ->where('u.merchant_id', $request->merchantId)
            ->where('l.city', '<>', '')
            ->field('l.province, l.city, COUNT(DISTINCT l.user_id) as user_count')
            ->group('l.province, l.city')
            ->order('user_count', 'desc')
            ->limit(10)
            ->select()
            ->toArray();
            
        $stats = [
            'province' => $provinceStats,
            'city' => $cityStats
        ];
        
        // 缓存结果1小时
        Cache::set($cacheKey, $stats, 3600);
        
        return $this->success('获取成功', $stats);
    }
} 